package com.wanjia.estate.service;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.wanjia.estate.constant.DocumentType;
import com.wanjia.estate.exception.ControllerException;
import com.wanjia.estate.pojo.bdc.SetDzcl;
import com.wanjia.estate.pojo.tax.A006;
import com.wanjia.estate.pojo.tax.A014;
import com.wanjia.estate.pojo.tax.A020;
import com.wanjia.estate.properties.FolderPathProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;


@Service
@Slf4j
public class TaxShiftService {

    @Autowired
    FolderPathProperties folderPathProperties;

    /**
     * 根据A014返回数据拿到文件数据
     * 文件数据保存到文件中
     * 读取文件进行Base64到PDF转换
     * @param response
     * @return
     */
    public List<String> base64PdfToPathService(A014.Response response) throws IOException {
        A014.TaxbizmlFourteen taxbizml = response.getTaxbizml();
        List<A014.Fcjysbxxlist> list = taxbizml.getFcjysbxxlist();
        A014.Fcjysbxxlist fcjysbxxlist = list.get(0);
        if (!fcjysbxxlist.getFhm().equals("0")){
            throw new ControllerException("获取申报表失败");
        }
        List<A014.Fcjysbfjxxlist> fcjysbfjxxlistList = taxbizml.getFcjysbfjxxlist();

        String pdfpath = folderPathProperties.getPdfpath();

        String filename = "wjsj/";

        List<String> filenameList = new ArrayList<>();
        for (A014.Fcjysbfjxxlist fcjysbfjxxlist : fcjysbfjxxlistList) {
            String wjsj = fcjysbfjxxlist.getWjsj(); //PDF 文件的 base64 编码
            String yxwj = JSON.parseObject(wjsj).getString("YXWJ");

            int index = 0;
            File parent = new File(pdfpath+filename);
            if (!parent.exists()) {
                // 没有父目录时，直接创建
                FileUtil.mkdir(parent);
            } else {
                // 遍历检索文件名
                while (new File(pdfpath+filename+index+".txt").exists()) {
                    index++;
                }
            }
            String filePath =pdfpath+filename+index+".txt";
            try {
                // 创建文件写入流
                BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));

                // 将Base64数据写入文件
                writer.write(yxwj);

                // 关闭流
                writer.close();

                log.info("Base64数据已写入文件： {}" , filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            FileInputStream fis = new FileInputStream(filePath);
            String data = IOUtils.toString(fis, "UTF-8");

            byte[] decodedBytes = Base64.getDecoder().decode(data);
            FileOutputStream fos = new FileOutputStream(pdfpath+filename+"zlf.pdf");
            fos.write(decodedBytes);
            fos.close();
            filenameList.add(filename+"zlf.pdf");
        }
        return filenameList;
    }


    /**
     * A006服务，根据影像材料名称查询材料
     * 补全A006.YXWJXX字段
     * @param yxclmc
     * @return
     */
    public A006.YXWJXX yxwjxxAddData(String yxclmc) throws IOException {
        String pdfpath = folderPathProperties.getPdfpath();
        String pdfFileName = DocumentType.getByClmc(yxclmc).key()+".pdf";
        String yxclmcpath=pdfpath+"/"+pdfFileName;
        log.info("影像材料文件路径：{}",yxclmcpath);
        File folder = new File(yxclmcpath);
        String base64String = convertToBase64(folder);
        log.info("已拿到base64");
        A006.YXWJXX yxwjxx=new A006.YXWJXX();
        yxwjxx.setZldm(DocumentType.getByClmc(yxclmc).zldm());
        yxwjxx.setYxwjbh("1");
        yxwjxx.setYxwjfilename(yxclmc);
        yxwjxx.setYxwjlx("PDF");
        yxwjxx.setSfbb("1");
        yxwjxx.setYxwjdz("data:application/pdf;base64,"+base64String);
        return yxwjxx;
    }

    private static String convertToBase64(File file) throws IOException {
        try (FileInputStream inputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            inputStream.read(bytes);
            return Base64.getEncoder().encodeToString(bytes);
        }
    }

    /**
     * A020完税证明地址获取
     * @param response
     * @return
     * @throws IOException
     */
    public String wszmPathService(A020.Response response) throws IOException {
        List<A020.Fcjyqswspzlist> fcjyqswspzlist = response.getTaxbizml().getFcjyqswspzlist();
        String fhm = fcjyqswspzlist.get(0).getFhm();
        if (!fhm.equals("0")){
            throw new ControllerException("获取申报表失败");
        }

        String pdfpath = folderPathProperties.getPdfpath();

        String filename = "wszm/";

        String wjsj = response.getTaxbizml().getQswsfjxxlist().get(0).getWjsj();
        String yxwj = JSON.parseObject(wjsj).getString("YXWJ");

        int index = 0;
            File parent = new File(pdfpath+filename);
            if (!parent.exists()) {
                // 没有父目录时，直接创建
                FileUtil.mkdir(parent);
            } else {
                // 遍历检索文件名
                while (new File(pdfpath+filename+index+".txt").exists()) {
                    index++;
                }
            }

            String filePath =pdfpath+filename+index+".txt";
            try {
                // 创建文件写入流
                BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));

                // 将Base64数据写入文件
                writer.write(yxwj);

                // 关闭流
                writer.close();

                log.info("Base64数据已写入文件： {}" , filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            FileInputStream fis = new FileInputStream(filePath);
            String data = IOUtils.toString(fis, "UTF-8");

            byte[] decodedBytes = Base64.getDecoder().decode(data);
            FileOutputStream fos = new FileOutputStream(pdfpath+filename+"完税证明.pdf");
            fos.write(decodedBytes);
            fos.close();

            return filename+"完税证明.pdf";
    }
}
